package com.xwq.xwqaiagent.config;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class MultiDataSourceConfig {

  /** 绑定并创建 MySQL 数据源 */
  @Bean
  @Primary
  @ConfigurationProperties("spring.datasource.primary")
  public DataSourceProperties primaryProperties() {
    return new DataSourceProperties();
  }

  @Bean
  @Primary
  public DataSource primaryDataSource() {
    return primaryProperties()
             .initializeDataSourceBuilder()
             .build();
  }

  /** 绑定并创建 PostgreSQL 数据源 */
  @Bean
  @ConfigurationProperties("spring.datasource.secondary")
  public DataSourceProperties secondaryProperties() {
    return new DataSourceProperties();
  }

  @Bean
  public DataSource secondaryDataSource() {
    return secondaryProperties()
             .initializeDataSourceBuilder()
             .build();
  }

  /** MySQL 上下文的 JdbcTemplate，其他组件默认注入 */
  @Bean
  @Primary
  public JdbcTemplate primaryJdbcTemplate(
      @Qualifier("primaryDataSource") DataSource ds) {
    return new JdbcTemplate(ds);
  }

  /** PostgreSQL 专用的 JdbcTemplate，供 PgVectorStore 使用 */
  @Bean
  public JdbcTemplate secondaryJdbcTemplate(
      @Qualifier("secondaryDataSource") DataSource ds) {
    return new JdbcTemplate(ds);
  }
}
